/******************************************************************************************************
Copyright (C) 2008 Mestrelab Research S.L. All rights reserved.

This file is part of the MNova scripting toolkit.

Authorized users of MNova Software may use this file freely, but this file is provided AS IS
with NO WARRANTY OF ANY KIND, INCLUDING THE WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE.
*****************************************************************************************************/
// This example function demonstrates how to apply some processing to a set of spectral files and to save the result in a single ASCII file.
/*jslint plusplus: true*/
/*global FileDialog, settings, TextStream, Dir, File, nmr, serialization, getMaskFiles, Application, NMRSpectrum, mainWindow*/


function import_process_saveOneAscii_loop() {
	"use strict";

	var procName, fileMask, dirMask, specDirKey, dirName, dir, outDirKey, saveDir, spec, fileName, fout, sout, lastOutName, files, fi, dw, flastOut, slastOut, si, ppm, dPpm, length;

	procName = "c:/procTemplates/proc.mnp"; // Processing file. It must be created in the Processing Template dialog of MestReNova.
	fileMask = "fid"; // This mask specifies files to be processed.
	dirMask = "*"; // This mask specifies directories to be scanned for spectra.

	// Select a directory with spectral data
	specDirKey = "import_process_saveOneAscii_loop/SpectraDir";
	dirName = FileDialog.getExistingDirectory(settings.value(specDirKey, Dir.home()), "Select Spectra Directory");

	if (!dirName) {
		return;
	}
	settings.setValue(specDirKey, dirName); // Save the directory name to be used another time the script is called

	dir = new Dir(dirName);
	dir.cdUp();

	// Select a file to save the output
	outDirKey = "import_process_saveOneAscii_loop/OutputDir";
	saveDir = settings.value(outDirKey, Dir.home()); // Get last used directory name
	fileName = FileDialog.getSaveFileName("ASCII Files (*.txt)", "Select Output File", saveDir);

	if (!fileName) {
		return;
	}

	// Open the selected file and create a text stream mapped to it
	fout = new File(fileName);
	settings.setValue(outDirKey, fout.absDirPath); // Save the directory name to be used another time the script is called
	sout = new TextStream(fout);
	sout.precision = 10;

	// Temporary file name
	lastOutName = Dir.temp() + "/import_process_saveOneAscii_loop.lastOut.tmp";
	if (File.exists(lastOutName)) {
		File.remove(lastOutName);
	}

	// The below function getMaskFiles is located in the files.qs script.
	files = getMaskFiles(dirName, dir.absPath, fileMask, dirMask, true);
	files.sort(Dir.numericPathsCompare);

	for (fi = 0, length = files.length; fi < length; fi++) {

		dw = mainWindow.newWindow(); // Create new document window
		if (serialization.open(files[fi])) {

			nmr.process(procName); // Apply processing template
			spec = new NMRSpectrum(nmr.activeSpectrum());

			fout.open(File.WriteOnly);

			flastOut = new File(lastOutName);
			slastOut = new TextStream(flastOut);
			if (!fi) {
				// Put fist column of the file in ppm. The scale is taken from the first spectrum.
				flastOut.open(File.WriteOnly);
				slastOut.precision = 10;

				ppm = spec.hz() / spec.frequency();
				dPpm = spec.scaleWidth() / spec.count() / spec.frequency();
				for (si = spec.count() - 1; si >= 0; si--) {
					slastOut.write(ppm, "\n");
					ppm += dPpm;
				}
				flastOut.close();
			}
			flastOut.open(File.ReadOnly);

			for (si = spec.count() - 1; si >= 0; si--) {
				sout.write(slastOut.readLine(), "\t\t", spec.real(si), "\n");
			}

			fout.close();
			flastOut.close();
			flastOut.remove();
			if (fi < length - 1) {
				File.copy(fileName, lastOutName);
			}
		}
		dw.close(); // Close document window of processed spectrum
	}
}
